package neatlogic.module.change.api;

import neatlogic.framework.auth.core.AuthAction;
import neatlogic.framework.change.dto.*;
import neatlogic.framework.common.constvalue.ApiParamType;
import neatlogic.framework.common.constvalue.GroupSearch;
import neatlogic.framework.exception.type.ParamIrregularException;
import neatlogic.framework.process.auth.PROCESS_BASE;
import neatlogic.framework.process.dto.ProcessTaskStepVo;
import neatlogic.framework.process.exception.process.ProcessStepUtilHandlerNotFoundException;
import neatlogic.framework.process.stephandler.core.IProcessStepHandlerUtil;
import neatlogic.framework.process.stephandler.core.IProcessStepInternalHandler;
import neatlogic.framework.process.stephandler.core.ProcessStepInternalHandlerFactory;
import neatlogic.framework.restful.annotation.Description;
import neatlogic.framework.restful.annotation.Input;
import neatlogic.framework.restful.annotation.OperationType;
import neatlogic.framework.restful.annotation.Param;
import neatlogic.framework.restful.constvalue.OperationTypeEnum;
import neatlogic.framework.restful.core.privateapi.PrivateApiComponentBase;
import neatlogic.framework.change.constvalue.ChangeAuditDetailType;
import neatlogic.framework.change.constvalue.ChangeAuditType;
import neatlogic.framework.change.constvalue.ChangeOperationType;
import neatlogic.framework.change.constvalue.ChangeProcessStepHandlerType;
import neatlogic.module.change.dao.mapper.ChangeMapper;
import neatlogic.framework.change.exception.ChangeNoPermissionException;
import neatlogic.framework.change.exception.ChangeStepNotFoundException;
import neatlogic.module.change.service.ChangeService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Objects;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
@AuthAction(action = PROCESS_BASE.class)
@OperationType(type = OperationTypeEnum.OPERATE)
public class ChangeStepUpdateApi extends PrivateApiComponentBase {

	@Autowired
	private ChangeMapper changeMapper;
	
	@Autowired
	private ChangeService changeService;

	@Autowired
	private IProcessStepHandlerUtil IProcessStepHandlerUtil;

	@Override
	public String getToken() {
		return "change/step/update";
	}

	@Override
	public String getName() {
		return "更新变更步骤";
	}

	@Override
	public String getConfig() {
		return null;
	}

	@Input({
		@Param(name = "processTaskStepId", type = ApiParamType.LONG, desc = "工单步骤id"),
		@Param(name = "changeStepId", type = ApiParamType.LONG, isRequired = true, desc = "变更步骤id"),
		@Param(name = "planStartDate", type = ApiParamType.STRING, desc = "计划开始日期"),
		@Param(name = "startTimeWindow", type = ApiParamType.STRING, desc = "开始时间窗口"),
		@Param(name = "endTimeWindow", type = ApiParamType.STRING, desc = "结束时间窗口"),
		@Param(name = "worker", type = ApiParamType.STRING, isRequired = true, minLength = 37, maxLength = 37, desc = "处理人或组"),
		@Param(name = "source", type = ApiParamType.STRING, defaultValue = "pc", desc = "来源")
	})
	@Description(desc = "更新变更步骤")
	@Override
	public Object myDoService(JSONObject jsonObj) throws Exception {
		Long changeStepId = jsonObj.getLong("changeStepId");
		ChangeStepVo changeStep = changeMapper.getChangeStepById(changeStepId);
		if(changeStep == null) {
			throw new ChangeStepNotFoundException(changeStepId);
		}
		/** 获取当前变更锁 **/
		changeMapper.getChangeLockById(changeStep.getChangeId());
		ChangeVo changeVo = changeMapper.getChangeById(changeStep.getChangeId());
		String owner = changeMapper.getChangeUserByChangeId(changeStep.getChangeId());
		if(StringUtils.isNotBlank(owner)) {
			changeVo.setOwner(GroupSearch.USER.getValuePlugin() + owner);
		}
		if(!changeService.isEditableChangeStep(changeVo, changeStep)) {
			throw new ChangeNoPermissionException(ChangeOperationType.EDITCHANGESTEP.getText());
		}
		/** 查出旧处理人或组 **/
		ChangeStepUserVo changeStepUserVo = changeMapper.getChangeStepUserByChangeStepId(changeStepId);
		if(changeStepUserVo != null && StringUtils.isNotBlank(changeStepUserVo.getUserVo().getUuid())) {
			changeStep.setWorker(GroupSearch.USER.getValuePlugin() + changeStepUserVo.getUserVo().getUuid());
		}else {
			ChangeStepTeamVo changeStepTeamVo = changeMapper.getChangeStepTeamByChangeStepId(changeStepId);
			if(changeStepTeamVo != null && StringUtils.isNotBlank(changeStepTeamVo.getTeamUuid())) {
				changeStep.setWorker(GroupSearch.TEAM.getValuePlugin() + changeStepTeamVo.getTeamUuid());
			}
		}

		ChangeStepVo changeStepVo = JSON.toJavaObject(jsonObj, ChangeStepVo.class);
		/** 更新变更步骤计划起止时间和时间窗口 **/
		changeStepVo.setId(changeStepId);	
		String worker = changeStepVo.getWorker();
		if(!worker.startsWith(GroupSearch.USER.getValuePlugin()) && !worker.startsWith(GroupSearch.TEAM.getValuePlugin())) {
			throw new ParamIrregularException("worker");
		}
		boolean isUpdate = false;
		if(!Objects.equal(changeStep.getWorker(), changeStepVo.getWorker())) {
			isUpdate = true;
			/** 删除旧变更步骤处理人或组**/
			changeMapper.deleteChangeStepUserByChangeStepId(changeStepId);
			changeMapper.deleteChangeStepTeamByChangeStepId(changeStepId);
			/** 更新变更步骤处理人或组 **/
			String[] split = worker.split("#");
			if(GroupSearch.USER.getValue().equals(split[0])) {
				changeMapper.insertChangeStepUser(new ChangeStepUserVo(changeStep.getChangeId(), changeStepId, split[1]));
			}else if(GroupSearch.TEAM.getValue().equals(split[0])) {
				changeMapper.insertChangeStepTeam(new ChangeStepTeamVo(changeStep.getChangeId(), changeStepId, split[1]));
			}
		}else if(!Objects.equal(changeStep.getPlanStartDate(), changeStepVo.getPlanStartDate())) {
			isUpdate = true;
		}else if(!Objects.equal(changeStep.getStartTimeWindow(), changeStepVo.getStartTimeWindow())) {
			isUpdate = true;
		}else if(!Objects.equal(changeStep.getEndTimeWindow(), changeStepVo.getEndTimeWindow())) {
			isUpdate = true;
		}
		
		if(isUpdate) {
			changeMapper.updateChangeStepById(changeStepVo);
			ProcessTaskStepVo currentProcessTaskStepVo = new ProcessTaskStepVo();
			ProcessTaskStepChangeVo processTaskStepChangeVo = changeMapper.getProcessTaskStepChangeHandleByChangeId(changeStep.getChangeId());
			if(processTaskStepChangeVo != null) {
				currentProcessTaskStepVo.setProcessTaskId(processTaskStepChangeVo.getProcessTaskId());
				if(Objects.equal(changeStep.getIsActive(), 1)) {
					IProcessStepInternalHandler processStepUtilHandler = ProcessStepInternalHandlerFactory.getHandler(ChangeProcessStepHandlerType.CHANGEHANDLE.getHandler());
					if (processStepUtilHandler == null) {
						throw new ProcessStepUtilHandlerNotFoundException(ChangeProcessStepHandlerType.CHANGEHANDLE.getHandler());
					}
					/** 更新变更步骤处理人时，触发更新processtask_step_worker和processtask_step_user数据 **/
					processStepUtilHandler.updateProcessTaskStepUserAndWorker(processTaskStepChangeVo.getProcessTaskId(), processTaskStepChangeVo.getProcessTaskStepId());
				}
			}else {
				Long processTaskId = changeMapper.getProcessTaskIdByChangeId(changeStep.getChangeId());
				currentProcessTaskStepVo.setProcessTaskId(processTaskId);
			}
			Long currentProcessTaskStepId = jsonObj.getLong("processTaskStepId");
			currentProcessTaskStepVo.setId(currentProcessTaskStepId);
			/** 生成活动 **/
			currentProcessTaskStepVo.getParamObj().put("changeStepName", changeStep.getName());
			currentProcessTaskStepVo.getParamObj().put(ChangeAuditDetailType.CHANGESTEPINFO.getParamName(), JSON.toJSONString(changeStepVo));
			currentProcessTaskStepVo.getParamObj().put(ChangeAuditDetailType.CHANGESTEPINFO.getOldDataParamName(), JSON.toJSONString(changeStep));
			currentProcessTaskStepVo.getParamObj().put("source", jsonObj.getString("source"));
			IProcessStepHandlerUtil.audit(currentProcessTaskStepVo, ChangeAuditType.EDITCHANGESTEP);
		}
	
		return null;
	}
}
